package com.gitee.qdbp.jdbc.test.condition;

import org.springframework.stereotype.Service;
import com.gitee.qdbp.jdbc.exception.UnsupportedFieldException;
import com.gitee.qdbp.jdbc.model.FieldScene;
import com.gitee.qdbp.jdbc.plugins.SqlDialect;
import com.gitee.qdbp.jdbc.plugins.WhereSqlBuilder;
import com.gitee.qdbp.jdbc.sql.SqlBuffer;
import com.gitee.qdbp.jdbc.sql.fragment.QueryFragmentHelper;
import com.gitee.qdbp.jdbc.test.service.EntityTools;
import com.gitee.qdbp.tools.utils.NamingTools;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 部门数据权限隔离SqlBuilder<br>
 * 如果不存在部门隔离字段, 那么就查询经办人=当前用户的记录<br>
 * 如果存在部门隔离字段, 那么就查询经办人=当前用户OR部门=指定部门的记录<br>
 *
 * @author zhaohuihua
 * @version 190308
 */
@Service
public class DeptIsolationBuilder implements WhereSqlBuilder<DeptIsolationWhere> {

    @Override
    public Class<DeptIsolationWhere> supported() {
        return DeptIsolationWhere.class;
    }

    @Override
    public SqlBuffer buildSql(DeptIsolationWhere condition, QueryFragmentHelper sqlHelper)
            throws UnsupportedFieldException {
        if (condition.isEmpty()) {
            return new SqlBuffer(); // 没有指定任何隔离字段, 没法加限制条件
        }

        String deptColumn = fieldNameToColumn(condition.getDeptField(), sqlHelper);
        String userColumn = fieldNameToColumn(condition.getUserField(), sqlHelper);
        String agentColumn = fieldNameToColumn(condition.getAgentField(), sqlHelper);

        SqlDialect dialect = sqlHelper.getSqlDialect();
        return EntityTools.buildDeptDataPermission(userColumn, agentColumn, deptColumn, dialect);
    }

    private static String fieldNameToColumn(String fieldName, QueryFragmentHelper sqlHelper) {
        if (VerifyTools.isBlank(fieldName)) {
            return fieldName;
        } else if (sqlHelper != null) {
            return sqlHelper.getColumnName(FieldScene.CONDITION, fieldName, true);
        } else {
            int dotIndex = fieldName.indexOf('.');
            if (dotIndex <= 0) {
                return NamingTools.toUnderlineString(fieldName).toUpperCase();
            } else {
                String prefix = fieldName.substring(0, dotIndex);
                String suffix = fieldName.substring(dotIndex + 1);
                return prefix + '.' + NamingTools.toUnderlineString(suffix).toUpperCase();
            }
        }
    }
}
